package cn.wzy.service.impl;

import cn.wzy.doc.CarDoc;
import cn.wzy.mapper.*;
import cn.wzy.pojo.*;
import cn.wzy.repository.CarDocRepository;
import cn.wzy.results.ResponseResult;
import cn.wzy.service.CarService;
import cn.wzy.utils.BaiduAuditUtils;
import cn.wzy.utils.BeanCopyUtils;
import cn.wzy.utils.LoginContext;
import cn.wzy.utils.VelocityUtils;
import cn.wzy.vo.GoPageVo;
import cn.wzy.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (Car)表服务实现类
 *
 * @author makejava
 * @since 2023-01-24 10:49:09
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {
@Resource
private CarTypeMapper carTypeMapper;
@Resource
private EmployeeMapper employeeMapper;
@Resource
private CarDetailMapper carDetailMapper;
@Resource
private ShopMapper shopMapper;
@Resource
private CarDocRepository carDocRepository;
@Resource
private CarOnlineAuditLogMapper carOnlineAuditLogMapper;
 public ResponseResult getCarPage(GoPageVo goPageVo) {
        Page<Car> page = new Page<>(goPageVo.getPageIndex(),goPageVo.getPageSize());
        LambdaQueryWrapper<Car> queryWrapper = new LambdaQueryWrapper<>();
        if (goPageVo.getKeyword()!=null && !"".equals(goPageVo.getKeyword())){
            queryWrapper.like(Car::getIsnew,goPageVo.getKeyword());
        }
        List<Car> productTypes = page(page, queryWrapper).getRecords();
     for (Car productType : productTypes) {
         CarType carType = carTypeMapper.selectById(productType.getTypeId());
         if (Objects.nonNull(carType))
         productType.setTypeName(carType.getName());
         Employee employee = employeeMapper.selectById(productType.getSellerId());
         if (Objects.nonNull(employee))
         productType.setSeller(employee.getUsername());
         productType.setUserId(LoginContext.getLoginAdmin().getId());
     }
        PageVo pageVo = new PageVo(productTypes, page.getTotal(), goPageVo.getPageSize());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    @Transactional
    public ResponseResult saveCar(Car car) {
        //        判断是否id存在，操作类型
        if (Objects.isNull(car.getId())){
//            添加操作
//            添加日志
            CarOnlineAuditLog carOnlineAuditLog = new CarOnlineAuditLog();
//            审核
            String title = car.getTitle();
            Map<String, Object> map = BaiduAuditUtils.TextCensor(title);
            if ((Boolean) map.get("success")){
                car.setAuditstate(1);
                carOnlineAuditLog.setState(1);
                carOnlineAuditLog.setAuditTime(new Date());
                carOnlineAuditLog.setNote("系统审核通过！！");
            }else {
                car.setAuditstate(2);
                carOnlineAuditLog.setState(2);
                carOnlineAuditLog.setAuditTime(new Date());
                carOnlineAuditLog.setNote("系统审核失败！！"+map.get("message"));
            }
            LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Shop::getId,car.getShopId());
            Shop shop = shopMapper.selectOne(queryWrapper);
            if (Objects.nonNull(shop))
            car.setShopname(shop.getName());
            car.setCreatetime(new Date());
            car.setState(0);
            car.setSellerId(LoginContext.getLoginAdmin().getId());
            car.setAuditstate(0);
            save(car);
//            日志，详情
            CarDetail carDetail = new CarDetail();
            carDetail.setInfo(car.getCarDetail().getInfo());
            carDetail.setCarId(car.getId());
            carDetail.setCartitle(car.getTitle());
            carDetailMapper.insert(carDetail);
            carOnlineAuditLog.setCarId(car.getId());
            carOnlineAuditLogMapper.insert(carOnlineAuditLog);
            return ResponseResult.okResult();
        }else {
//            修改操作
            //            添加日志
            CarOnlineAuditLog carOnlineAuditLog = new CarOnlineAuditLog();
//            审核
            String title = car.getTitle();
            Map<String, Object> map = BaiduAuditUtils.TextCensor(title);
            if ((Boolean) map.get("success")){
                car.setAuditstate(1);
                carOnlineAuditLog.setState(1);
                carOnlineAuditLog.setAuditTime(new Date());
                carOnlineAuditLog.setNote("系统审核通过！！");
            }else {
                car.setAuditstate(2);
                carOnlineAuditLog.setState(2);
                carOnlineAuditLog.setAuditTime(new Date());
                carOnlineAuditLog.setNote("系统审核失败！！"+map.get("message"));
            }
            LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Shop::getId,car.getId());
            Shop shop = shopMapper.selectOne(queryWrapper);
            if (Objects.nonNull(shop))
                car.setShopAdress(shop.getAddress());
            CarType carType = carTypeMapper.selectById(car.getTypeId());
            if (Objects.nonNull(carType))
                car.setTypeName(carType.getName());
            LambdaQueryWrapper<CarDetail> carDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            carDetailLambdaQueryWrapper.eq(CarDetail::getCarId,car.getId());
            car.setCarInfo(car.getCarDetail().getInfo());
            updateById(car);
//            日志，详情
            CarDetail carDetail = new CarDetail();
            carDetail.setInfo(car.getCarDetail().getInfo());
            carDetail.setCartitle(car.getTitle());
            carDetailMapper.updateById(carDetail);
            carOnlineAuditLog.setCarId(car.getId());
            carOnlineAuditLogMapper.insert(carOnlineAuditLog);
            CarDoc carDocs = BeanCopyUtils.copyBean(car, CarDoc.class);
//            判断是否上架，es操作
            if (car.getState()==1){
                carDocRepository.deleteById(car.getId());
                carDocRepository.save(carDocs);
            }
            return ResponseResult.okResult();
        }
    }

    @Transactional
    @Override
    public ResponseResult deleteCar(Long id) {
        //        日志
        Car car = getById(id);
        CarOnlineAuditLog carOnlineAuditLog = new CarOnlineAuditLog();
        carOnlineAuditLog.setCarId(car.getId());
        carOnlineAuditLog.setAuditTime(new Date());
        carOnlineAuditLog.setAuditId(LoginContext.getLoginAdmin().getId());
        carOnlineAuditLog.setNote("员工"+LoginContext.getLoginAdmin().getUsername()+"删除了车辆为"+car.getTitle());
        carOnlineAuditLog.setState(5);
        carOnlineAuditLogMapper.insert(carOnlineAuditLog);
//        删除
        removeById(id);
        LambdaQueryWrapper<CarDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CarDetail::getCarId,id);
        carDetailMapper.delete(queryWrapper);

//        删除es
        carDocRepository.deleteById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteCarList(List<Long> ids) {
       removeByIds(ids);
       return ResponseResult.okResult();
    }

    @Transactional
    @Override
    public ResponseResult onsale(List<Long> ids) {
//     获取审核状态，修改状态
        if (Objects.isNull(ids)||ids.size()==0){
            return ResponseResult.errorResult(500,"数据不存在，请选择数据操作");
        }
        List<Car> carList = listByIds(ids);
        List<Car> cars = carList.stream().filter(x -> x.getAuditstate() == 1).collect(Collectors.toList());
        if (Objects.isNull(cars)||cars.size()==0){
            return ResponseResult.errorResult(500,"全部都是审核不通过");
        }
        cars.stream().forEach(car -> {car.setState(1);car.setOnsaletime(new Date());});
        updateBatchById(cars);
//        添加es
        for (Car car : cars) {
            LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Shop::getId,car.getShopId());
            Shop shop = shopMapper.selectOne(queryWrapper);
            if (Objects.nonNull(shop))
            car.setShopAdress(shop.getAddress());
            CarType carType = carTypeMapper.selectById(car.getTypeId());
            if (Objects.nonNull(carType))
            car.setTypeName(carType.getName());
            LambdaQueryWrapper<CarDetail> carDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            carDetailLambdaQueryWrapper.eq(CarDetail::getCarId,car.getId());
            CarDetail carDetail = carDetailMapper.selectOne(carDetailLambdaQueryWrapper);
            if (Objects.nonNull(carDetail))
            car.setCarInfo(carDetail.getInfo());
        }
        List<CarDoc> carDocs = BeanCopyUtils.copyBeanList(cars, CarDoc.class);
        carDocRepository.saveAll(carDocs);
//        添加上传日志
        for (Car car : cars) {
            CarOnlineAuditLog carOnlineAuditLog = new CarOnlineAuditLog();
            carOnlineAuditLog.setCarId(car.getId());
            carOnlineAuditLog.setAuditTime(new Date());
            carOnlineAuditLog.setAuditId(LoginContext.getLoginAdmin().getId());
            carOnlineAuditLog.setNote("员工"+LoginContext.getLoginAdmin().getUsername()+"上架了车辆为"+car.getTitle());
            carOnlineAuditLog.setState(3);
            carOnlineAuditLogMapper.insert(carOnlineAuditLog);
        }
        // 生成静态页面
        staticPage(cars);
        return ResponseResult.okResult("上架成功数："+cars.size()+"失败数："+(ids.size()-cars.size()));
    }

    @Override
    public ResponseResult offsale(List<Long> ids) {
//     直接修改数据库状态
        List<Car> cars = listByIds(ids);
        cars.stream().forEach(x->{x.setState(0);x.setOffsaletime(new Date());});
        updateBatchById(cars);
//        es删除
        for (Car car : cars) {
            carDocRepository.deleteById(car.getId());
        }
//        日志
        for (Car car : cars) {
            CarOnlineAuditLog carOnlineAuditLog = new CarOnlineAuditLog();
            carOnlineAuditLog.setCarId(car.getId());
            carOnlineAuditLog.setAuditTime(new Date());
            carOnlineAuditLog.setAuditId(LoginContext.getLoginAdmin().getId());
            carOnlineAuditLog.setNote("员工"+LoginContext.getLoginAdmin().getUsername()+"下架了车辆为"+car.getTitle());
            carOnlineAuditLog.setState(4);
            carOnlineAuditLogMapper.insert(carOnlineAuditLog);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getCar(Long id) {
       Car car = getById(id);
       return ResponseResult.okResult(car);
    }

    private void staticPage(List<Car> list) {
        String templateFilePathAndName = this.getClass().getClassLoader().getResource("").getPath()+"/templates/carDetail.vm";
        String targetFilePath = "D:\\car_sys_vue\\car_web\\cardetails\\";
        // 每个车辆都要生成静态页面
        for (Car car : list) {
            VelocityUtils.staticByTemplate(car,templateFilePathAndName,targetFilePath+car.getId()+".html");
        }
    }
}

